package com.example.android_20190610_01;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.os.Binder;
import android.os.IBinder;
import android.app.Service;
import android.content.Intent;

public class BindService extends Service {
    private int count;
    private boolean quit;
//    定义onBinder方法所返回的对象
    private MyIBinder binder=new MyIBinder();
//----------通过继承Binder来实现IBinder类----------------
    public class MyIBinder extends Binder
    {
        public int getCount()
        {
//            获取Service的运行状态：count
            return count;
        }
    }
//--------onBind方法------------------------------
    public IBinder onBind(Intent intent) {
        System.out.println("Service is Binded!");
        return binder;    //返回IBinder对象
    }
//    Service被创建时回调该方法

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("Service is Created.");
//---------启动一条线程，动态修改count状态值
        new Thread()
        {
            @Override
            public void run()
            {
                while(!quit)    //标识Service关闭启动状态
                {
                    try
                    {
                        Thread.sleep(1000);
                    }catch(InterruptedException e) { }
                    count++;
                }
            }
        }.start();
    }
//--------Service被断开连接时回调该方法---------------------------
    @Override
    public boolean onUnbind(Intent intent)
    {
        System.out.println("Service is Unbinded");
        return true;
    }
//--------Service被关闭之前回调------------------------------------
    @Override
    public void onDestroy() {
        super.onDestroy();
        this.quit=true;
        System.out.println("Service is Destroy");
    }
}
